﻿using System;
using System.Linq;
using System.Linq.Expressions;
using Tss.MagicWeb.Domain.Abstract;
using Tss.MagicWeb.Domain.Entities;

namespace Tss.MagicWeb.Domain.Concrete
{
    public class UserRepository : IUserRepository, IDisposable
    {
        private MagicWebInterfaceEntities context = new MagicWebInterfaceEntities();

        public User Read(Int64 id)
        {
            return context.Users.FirstOrDefault(u => u.Id == id);
        }

        public IQueryable<User> Query()
        {
            return context.Users;
        }

        public IQueryable<User> Query(Expression<Func<User, Boolean>> filter)
        {
            return context.Users.Where(filter);
        }

        public void Create(User entity)
        {
            context.AddToUsers(entity);
            context.SaveChanges();
        }

        public void Delete(User entity)
        {
            context.Users.DeleteObject(entity);
            context.SaveChanges();
        }

        public void Update(User entity)
        {
            context.SaveChanges();
        }

        public User ReadByCredentials(string login, string password)
        {
            return context.Users.FirstOrDefault(u => u.Login == login && u.Password == password);
        }

        public User ReadByLogin(string login)
        {
            return context.Users.FirstOrDefault(u => u.Login == login);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool cleanManaged)
        {
            if (cleanManaged)
            {
                if (context != null)
                {
                    context.Dispose();
                }   
            }
        }
    }
}
